﻿using JZ_UDI.DataAccess;
using JZ_UDI.DataAccess.DataEntity;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NLog;
using LogLevel = NLog.LogLevel;

namespace JZ_UDI.View.Settings
{
    public partial class frmVendorCodeAdd : UIForm
    {

        public delegate void AddFinishFormClose(object sender,string vendorcode);
        public event AddFinishFormClose addFormClose;

        public frmVendorCodeAdd()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            using (var context = new EFDbContext())
            {
                List<VendorCode> lists = context.VendorCodes.ToList();
                VendorCode vc = new VendorCode();
                vc.Vendor_Code = txtVendorCode.Text.Trim();
                vc.ActivatedState = "否";
                vc.isDeleted = 0;
                if (!lists.Contains(vc))
                {
                    context.VendorCodes.Add(vc);
                    int count=context.SaveChanges();
                    if (count <= 0)
                    {
                        Global.SaveLogger(LogLevel.Error, Global.logger.Name, "添加" + vc.Vendor_Code + "厂商代码失败");
                        throw new DbUpdateException("厂商代码添加失败!");
                    }
                    else
                    {
                        // 触发事件，传递结果给订阅者  
                        addFormClose?.Invoke(this, txtVendorCode.Text.Trim());
                        Global.SaveLogger(LogLevel.Error, Global.logger.Name, "添加" + vc.Vendor_Code + "厂商代码成功");
                    }
                }

            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
    }
}
